const express = require('express');
const mysqlUtil = require('../../mysql/mysql-util');
const utilFunc = require('../../utilFunc');
const router = express.Router();
const jwtHandle = require("../../utilFunc/jwtHandle");
// 文件上传
const fs = require('fs');
const formidable = require('formidable');

router.post('/create', (req, res) =>{
    const headers = req.headers;
    const token = headers['xylo-token'];
    const data = utilFunc.getResponseData();
    jwtHandle.getUserIdByjwtVerify(token, (userId) => {
        const info = req.query;
        console.log(info);
        const sql = `INSERT INTO articles (
            user_id, 
            article_title, 
            type, 
            article_categorys, 
            cover_img_url,
            article_des, 
            article_content, 
            article_date, 
            last_edit_date, 
            article_views ) VALUES(
            '${userId}', 
            '${info.article_title}', 
            '${info.type}',
            '${info.cover_img_url}',
            '${info.article_categorys}', 
            '${info.article_des}', 
            '${info.article_content}',
            '${info.article_date}',
            '${info.last_edit_date}',
            0
            )`;
        mysqlUtil.query(sql, (err, result) => {
            if (err) { return console.log("查询数据库菜单报错！"); }
            data.code = 200;
            data.message = '发布成功！';
            res.send(data);
        })
    }, (e) => {
        res.status(401);
        data.code = 401;
        data.message = '兄弟， 过期了， 你的token！';
        res.send(data);
        return;
    });
})

router.post('/read', (req, res) =>{
    const headers = req.headers;
    const token = headers['xylo-token'];
    const data = utilFunc.getResponseData();

    jwtHandle.getUserIdByjwtVerify(token, (userId) => {
        const sql = `SELECT id, 
                        user_id, 
                        article_title, 
                        type, 
                        article_categorys, 
                        article_date,
                        cover_img_url,
                        last_edit_date, 
                        article_views
             FROM articles WHERE user_id = ${userId};`;
        mysqlUtil.query(sql, (err, result) => {
            if (err) { return console.log("查询数据库菜单报错！"); }
            data.code = 200;
            data.message = '成功！';
            result.sort((a, b) => {
             return b.last_edit_date - a.last_edit_date;
            })
            data.content = result;
            res.send(data);
        })
    }, (e) => {
        res.status(401);
        data.code = 401;
        data.message = '兄弟， 过期了， 你的token！';
        res.send(data);
        return;
    });
});
router.get('/articleDetail', (req, res) =>{
    const headers = req.headers;
    const token = headers['xylo-token'];
    const data = utilFunc.getResponseData();
    jwtHandle.getUserIdByjwtVerify(token, (userId) => {
        const info = req.query;
        const sql = `SELECT article_des, article_content FROM articles WHERE id = ${info.id};`;
        mysqlUtil.query(sql, (err, result) => {
            if (err) { return console.log(`删除id === ${info.id}文章报错！`); }
            data.code = 200;
            data.content = result;
            data.message = '查询详情成功！';
            console.log("查询详情成功！");
            res.send(data);
        })
    }, (e) => {
        res.status(401);
        data.code = 401;
        data.message = '兄弟， 过期了， 你的token！';
        res.send(data);
        return;
    });
});

router.post('/update', (req, res) =>{
    const headers = req.headers;
    const token = headers['xylo-token'];
    const data = utilFunc.getResponseData();
    jwtHandle.getUserIdByjwtVerify(token, (userId) => {
        const info = req.query;
        console.log(info);
        const sql = `UPDATE articles SET    article_title = '${info.article_title}',
                                            type = '${info.type}',
                                            article_categorys = '${info.article_categorys}',
                                            article_des = '${info.article_des}',
                                            cover_img_url = '${info.cover_img_url}',
                                            article_content = '${info.article_content}',
                                            last_edit_date = '${info.last_edit_date}'
                                WHERE id = ${info.id};`;
        mysqlUtil.query(sql, (err, result) => {
            if (err) { return console.log(`更新id === ${info.id}文章报错！`); }
            data.code = 200;
            data.content = result;
            data.message = '更新成功！';
            res.send(data);
        })
    }, (e) => {
        res.status(401);
        data.code = 401;
        data.message = '兄弟， 过期了， 你的token！';
        res.send(data);
        return;
    });
});

router.post('/delete', (req, res) =>{
    const headers = req.headers;
    const token = headers['xylo-token'];
    const data = utilFunc.getResponseData();
    jwtHandle.getUserIdByjwtVerify(token, (userId) => {
        const info = req.query;
        const sql = `DELETE FROM articles WHERE id = ${info.id};`;
        mysqlUtil.query(sql, (err, result) => {
            if (err) { return console.log(`删除id === ${info.id}文章报错！`); }
            data.code = 200;
            data.content = result;
            data.message = '删除成功！';
            res.send(data);
        })
    }, (e) => {
        res.status(401);
        data.code = 401;
        data.message = '兄弟， 过期了， 你的token！';
        res.send(data);
        return;
    });
});

router.post('/uploads/cover', (req, res) =>{
    const headers = req.headers;
    const token = headers['xylo-token'];
    const data = utilFunc.getResponseData();
    // jwtHandle.getUserIdByjwtVerify(token, (userId) => {
        var form = new formidable.IncomingForm();
        form.parse(req, (err, fileds, files) => {
            //  fileds ： {}
            // files: 前端传过来的具体信息
            const fileName = files.file.name;
            const tempPath = files.file.path;
            const serverStatileBaseUrl = 'static/xylo-blog-service';
            // 判断是否已经存在该文件夹
            if (!fs.existsSync(serverStatileBaseUrl)) {
                fs.mkdirSync(serverStatileBaseUrl);
            }
            const localCacheFiles = serverStatileBaseUrl + '/uploads';  // 本地存储路径
            // 判断是否已经存在该文件夹
            if (!fs.existsSync(localCacheFiles)) {
                fs.mkdirSync(localCacheFiles);
            }
            const rs = fs.createReadStream(tempPath);   // 可读流
            const localCacheUrl = './' + localCacheFiles + '/' + fileName;
            const ws = fs.createWriteStream(localCacheUrl); // 可写流

            rs.pipe(ws);
            data.code = 200;
            const responseUrl = 'uploads/' + fileName;
            data.content = {
                url: responseUrl,
                name: fileName
            };
            data.message = '上传成功';
            res.send(data);
        })
    // }, (e) => {
    //     res.status(401);
    //     data.code = 401;
    //     data.message = '兄弟， 过期了， 你的token！';
    //     res.send(data);
    //     return;
    // });
});

router.post('/lastCreate', (req, res) =>{
    const headers = req.headers;
    const token = headers['xylo-token'];
    const data = utilFunc.getResponseData();
    jwtHandle.getUserIdByjwtVerify(token, (userId) => {
        const sql = `select * from articles order by id DESC limit 1`;
        mysqlUtil.query(sql, (err, result) => {
            if (err) { return console.log("查询数据库菜单报错！"); }
            data.code = 200;
            data.content = result;
            data.message = '获取最新一条数据成功';
            res.send(data);
        })
    }, (e) => {
        res.status(401);
        data.code = 401;
        data.message = '兄弟， 过期了， 你的token！';
        res.send(data);
        return;
    });
});

module.exports = router;